package com.zanfeng.signleplatform.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.github.pagehelper.Page;
import com.zanfeng.signleplatform.common.bean.PageResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CoreUtil {


    /**
     * 字符串数组转int列表
     *
     * @param array
     * @return
     */
    public static List<Integer> toIntegerList(String[] array) {
        List<Integer> list = new ArrayList<Integer>();
        if (array != null && array.length > 0) {
            for (String str : array) {
                list.add(Integer.valueOf(str));
            }
        }
        return list;
    }


    public static <T> Map<String, T> listToMap(List<T> list, String key) {
        Map<String, T> map = new HashedMap();
        for (T object : list) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);
            if (jsonObject.containsKey(key)) {
                map.put(jsonObject.getString(key), object);
            }
        }
        return map;
    }


    /**
     * 拆分列表
     *
     * @param targeList
     * @param size
     * @return
     */
    public static List<List<String>> subList(List<String> targeList, int size) {
        List<List<String>> listArr = new ArrayList<List<String>>();
        //获取被拆分的数组个数
        int arrSize = targeList.size() % size == 0 ? targeList.size() / size : targeList.size() / size + 1;
        for (int i = 0; i < arrSize; i++) {
            List<String> sub = new ArrayList<String>();
            //把指定索引数据放入到list中
            for (int j = i * size; j <= size * (i + 1) - 1; j++) {
                if (j <= targeList.size() - 1) {
                    sub.add(targeList.get(j));
                }
            }
            listArr.add(sub);
        }
        return listArr;
    }


    //  TODO 本地线程对象
    private static Mapper dozerMapper = DozerBeanMapperBuilder.buildDefault();


    public static Mapper getDozerMapper() {
        return dozerMapper;
    }

    public synchronized static Page toList(Page sourcePage, Class targetClass) {
        if (sourcePage != null) {
            List list = new ArrayList();
            for (Object obj : sourcePage) {
                Object target = dozerMapper.map(obj, targetClass);
                list.add(target);
            }
            sourcePage.clear();
            sourcePage.addAll(list);
        }
        return sourcePage;
    }

    public synchronized static PageResult toList(PageResult sourcePage, Class targetClass) {
        PageResult resultPage = new PageResult();
        if (sourcePage != null) {
            List list = new ArrayList();
            for (Object obj : sourcePage.getList()) {
                Object target = dozerMapper.map(obj, targetClass);
                list.add(target);
            }
            resultPage.getList().clear();
            resultPage.getList().addAll(list);
            resultPage.setPager(sourcePage.getPager());
        }
        return resultPage;
    }

    public synchronized static List toList(List listData, Class targetClass) {
        List list = new ArrayList();
        if (listData != null) {
            for (Object obj : listData) {
                Object target = dozerMapper.map(obj, targetClass);
                list.add(target);
            }

        }
        return list;
    }

    public synchronized static <T> T toVO(Object sourceObj, Class<T> targetClass) {
        if (sourceObj != null) {
            return dozerMapper.map(sourceObj, targetClass);
        }
        return null;
    }


    public static <T> T fsignleplatformtOne(List<T> beanList) {
        if (CollectionUtils.isNotEmpty(beanList)) {
            return beanList.get(0);
        }
        return null;
    }


    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    }


    public static String unicode2String(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);
            // 追加成string
            string.append((char) data);
        }
        return string.toString();
    }

    public static final String LOCALHOST = "localhost";

    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || LOCALHOST.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || LOCALHOST.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Forwarded-For");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || LOCALHOST.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Real-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || LOCALHOST.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }


    //  过滤列表
    private static Stream streamList(List sourceList) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Stream.empty();
        }
        return sourceList.stream();
    }

    /**
     * 转换数据对象列表列表
     *
     * @param aList  来源列表
     * @param mapper 对象转换器
     * @param <T>    转换前对象（如：IO）
     * @param <R>    转换后对象（如：Result）
     * @return
     */
    public static <T, R> List<R> streamConverterList(List<T> aList, Function<? super T, ? extends R> mapper) {
        if (CollectionUtils.isEmpty(aList)) {
            return new ArrayList<>();
        }
        return aList.stream().map(mapper).collect(Collectors.toList());
    }

    public static <T> void handleFilterIfNotEmpty(Stream<T> stream, Predicate<? super T> predicate) {
        List<T> list = stream.filter(predicate).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(list)) {

        }
    }

}
